#!/bin/bash

GLOBAL_KEY_HASH_FILE="efuse_key_hash.tmp"
GLOBAL_MTK_FDTGET="${PWD}/../mtktools/fdtget"
GLOBAL_MTK_EXTRACT_REGGION="${PWD}/../mtktools/extract_region"
GLOBAL_EFUSE_EXCEL="Apoo_SystemDesign_EFUSE.xlsx"

## echo_hex function
# $1: hex string, char number must be even
#     For example: 'A55A5AA5'
# OUT: binary stream of hex string
# ret: 0  - succeed
#      !0 - fail
echo_hex()
{
	# Check parameter number
	if [ 1 -ne $# ]; then
		return 1
	fi

	# Check whether parameter is hex string
	if ! (echo $1 | grep '^[0-9A-Fa-f]\+$') >/dev/null 2>&1; then
		return 2
	fi

	local CHAR_NUM=`echo -n $1 | wc -c`
	# Check char number of hex string
	if [ 0 -ne $((${CHAR_NUM} % 2)) ]; then
		return 3
	fi
	echo -en "`echo $1 | sed 's/../\\\x&/g'`"
}


split_str_to_quadbytes() {
        quadbytes=""
        sed_cmd="sed s,\(..\)\(..\)\(..\)\(..\),\1\2\3\4,g"
        if [ ! -z "$1" ]; then
            for i in $(seq 1 8 ${#1}); do
                    end_idx=`echo "${i} + 7" | bc`
                    qb=`echo ${1} | cut -c${i}-${end_idx} | ${sed_cmd}`
                    quadbytes="${quadbytes} ${qb}"
            done
        fi

        echo -n $quadbytes
}

gen_sbc_key_hash() {
        FDT_IMG=$1
        TMP_FILE=$(mktemp col_rgn.bin.XXXXXX)

        DEF_CONF=`${GLOBAL_MTK_FDTGET} -t s ${FDT_IMG} /configurations default`
        SIG_NODE=`${GLOBAL_MTK_FDTGET} -l ${FDT_IMG} /configurations/${DEF_CONF}`
        KEY_HINT=`${GLOBAL_MTK_FDTGET} -t s ${FDT_IMG} /configurations/${DEF_CONF}/${SIG_NODE} key-name-hint`
        SHAX=`${GLOBAL_MTK_FDTGET} -t s ${FDT_IMG} /configurations/${DEF_CONF}/${SIG_NODE} algo | cut -d, -f1`
        ${GLOBAL_MTK_EXTRACT_REGGION} ${FDT_IMG} ${TMP_FILE} /signature/key-${KEY_HINT}
        KEY_HASH=`${SHAX}sum ${TMP_FILE} | cut -d " " -f 1`
        echo "Hash algo: ${SHAX}"
        echo "key_hash: ${KEY_HASH}"

        echo -n "$(split_str_to_quadbytes ${KEY_HASH})" > ${GLOBAL_KEY_HASH_FILE};rm -f ${TMP_FILE}
}

gen_sbc_key_hash $1
python3 geteFusedata.py ${GLOBAL_KEY_HASH_FILE} ${GLOBAL_EFUSE_EXCEL};echo_hex "$(cat eFusedata)" > "eFusedata.tmp";mv "eFusedata.tmp" "eFusedata"
rm -f ${GLOBAL_KEY_HASH_FILE}
